package com.hyy.blogtest.common.intercepter;

import com.hyy.blogtest.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginIntercpter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //从请求中获取token
        String token = request.getHeader("user_header_token");
        log.info("前端请求中得到的token：{}", token);

        //解析token
        Claims claims= JwtUtil.parseToken(token);
        if(claims==null){
            log.error("前端给的token是无效的");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//未授权401
            return false;
        }

        //可以在进行claims的判断，这里不做了

        return true;
    }
}
